package com.guiwu.gteway.industryapp.Device.View;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.guiwu.gteway.industryapp.Api.GuiwuApi;
import com.guiwu.gteway.industryapp.Api.GuiwuApiCallback;
import com.guiwu.gteway.industryapp.Device.module.AlarmBean;
import com.guiwu.gteway.industryapp.R;
import com.guiwu.gteway.industryapp.util.MyLog;
import com.guiwu.gteway.industryapp.widget.CustomDatePicker;
import com.guiwu.gteway.industryapp.widget.SearchEditText;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * Created by qiaoguan on 2018/3/8. 监控点报警记录
 */

public class MonitorAlarmFragment extends Fragment implements SegmentedGroup.OnCheckedChangeListener, View.OnClickListener
                                                                ,SearchEditText.OnSearchClickListener{

    private static final String TAG = "MonitorAlarmFragment";

    private SegmentedGroup radioGroup;
    private RadioButton nowBt, historyBt;
    private LinearLayout searchLayout,timePickLayout;
    private static final int FLAG_NOW = 0x01;
    private static final int FLAG_HISTORY = 0x02;
    private int pageFlag;

    private String gateWaySn;
    private MonitorActivity activityParent;

    private XRecyclerView refreshView;
    private MyAdapter refreshAdapter;
    private List<AlarmBean> alarmNowShow = new ArrayList<>();
    private List<AlarmBean> alarmHistory = new ArrayList<>();
    private List<AlarmBean> alarmShowCopy = new ArrayList<>();

    private Button alarmStartBt ,alarmEndBt;
    private Date dateNow, dateStart;
    private CustomDatePicker datePickerStart, datePickerEnd;
    private SimpleDateFormat sf;


    public SearchEditText searchEditText;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityParent = (MonitorActivity) getActivity();
        gateWaySn = getArguments().getString(MonitorActivity.GATEWAY_SN);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.monitor_alarm_layout,container,false);
        initView(view);
        return view;
    }

    private void initView(View view){
        searchLayout = view.findViewById(R.id.alarm_search);
        searchLayout.setVisibility(View.GONE);
        searchEditText = view.findViewById(R.id.alarm_search_et);
        searchEditText.setOnSearchClickListener(this);
        timePickLayout = view.findViewById(R.id.alarm_select_time);
        timePickLayout.setVisibility(View.GONE);
        radioGroup = view.findViewById(R.id.segment_bt);
        radioGroup.setOnCheckedChangeListener(this);
        nowBt = view.findViewById(R.id.radio_now);
        historyBt = view.findViewById(R.id.radio_history);
        nowBt.setChecked(true);
        pageFlag = FLAG_NOW;

        alarmStartBt = view.findViewById(R.id.alarm_time_start);
        alarmStartBt.setOnClickListener(this);
        alarmEndBt = view.findViewById(R.id.alarm_time_end);
        alarmEndBt.setOnClickListener(this);

        initRefresh(view);
        initTime();
    }

    private void initRefresh(View view){
        View headView = LayoutInflater.from(getContext()).inflate(R.layout.alarm_head_view,null);
        refreshView = view.findViewById(R.id.alarm_refresh_view);
        LinearLayoutManager xManager = new LinearLayoutManager(getContext());
        xManager.setOrientation(LinearLayoutManager.VERTICAL);
        refreshView.setLoadingMoreEnabled(false);
        refreshView.setLayoutManager(xManager);
        MonitorActivity.stopParentScroll(refreshView);
        MonitorActivity.stopParentScroll(headView);
        refreshView.addHeaderView(headView);
        refreshView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (pageFlag == FLAG_NOW){
                    getAlarmNow();
                }else{
                    getAlarmHistory();
                }

            }
            @Override
            public void onLoadMore() {

            }
        });
        refreshView.addItemDecoration(new android.support.v7.widget.DividerItemDecoration(activityParent,LinearLayoutManager.VERTICAL));

    }

    private void initTime(){
        sf = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.getDefault());
        dateNow = new Date();
        dateStart = new Date(dateNow.getTime() - 24*60*60*1000);
        String now = sf.format(dateNow);
        String start = sf.format(dateStart);
        alarmStartBt.setText(start);
        alarmEndBt.setText(now);

        datePickerStart = new CustomDatePicker(getContext(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                dateStart = pressDate(time);
                alarmStartBt.setText(time);
                if (checkDate(dateStart,dateNow)){
                    getAlarmHistory();
                }
            }
        },"2010-01-01 00:00",start);
        datePickerStart.showSpecificTime(true);
        datePickerStart.setIsLoop(false);

        datePickerEnd = new CustomDatePicker(getContext(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                dateNow = pressDate(time);
                alarmEndBt.setText(time);
                if (checkDate(dateStart,dateNow)){
                    getAlarmHistory();
                }
            }
        },"2010-01-01 00:00",now);
        datePickerEnd.showSpecificTime(true);
        datePickerEnd.setIsLoop(false);
    }

    private Date pressDate(String dateString){
        Date date = null;
        try {
            date = sf.parse(dateString);
        }catch (ParseException e){
            e.printStackTrace();
            MyLog.i(TAG ,"转换时间格式失败" + dateString);
        }
        return date;
    }
    private boolean checkDate(Date dateStart ,Date dateEnd){
        if (dateEnd.before(dateStart)){
            Toast.makeText(getContext(),getString(R.string.pick_error),Toast.LENGTH_SHORT).show();
            return false;
        }else
            return true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.alarm_time_start:
                datePickerStart.show(alarmStartBt.getText().toString());
                break;
            case R.id.alarm_time_end:
                datePickerEnd.show(alarmEndBt.getText().toString());
                break;
        }
    }


    public void updateUI(){
        if (refreshAdapter == null){
            refreshAdapter = new MyAdapter(alarmNowShow);
            refreshView.setAdapter(refreshAdapter);
        }else {
            refreshAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        refreshView.refresh();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.radio_now:
                pageFlag = FLAG_NOW;
                searchLayout.setVisibility(View.GONE);
                timePickLayout.setVisibility(View.GONE);
                if (refreshView != null){
                    refreshView.setPullRefreshEnabled(true);
                    refreshAdapter.clearContent();
                    refreshView.refresh();
                }

                break;
            case R.id.radio_history:
                pageFlag = FLAG_HISTORY;
                searchLayout.setVisibility(View.VISIBLE);
                timePickLayout.setVisibility(View.VISIBLE);
                refreshAdapter.clearContent();
                if (refreshView != null){
                 //   refreshView.setPullRefreshEnabled(false);
                    refreshView.refresh();
                }
                break;
        }
    }

    @Override
    public void onSearchClick(View view) {
        switch (view.getId()){
            case  R.id.alarm_search_et:
                queryMatchShow(((EditText)view).getText().toString());
        }
    }


    //refresh view 的item适配器
    private class MyViewHolder extends RecyclerView.ViewHolder{
      private  TextView alarmName ,alarmState,alarmValue,alarmTimeYear,alarmTimeHour;
      private  SimpleDateFormat sfYear, sfHour;

        public MyViewHolder(View itemView) {
            super(itemView);
            initItemView();
            initRule();
        }

        private void initItemView(){
            alarmName = itemView.findViewById(R.id.alarm_item_name);
            alarmState = itemView.findViewById(R.id.alarm_item_state);
            alarmValue = itemView.findViewById(R.id.alarm_item_value);
            alarmTimeYear = itemView.findViewById(R.id.alarm_item_time_year);
            alarmTimeHour = itemView.findViewById(R.id.alarm_item_time_hour);
        }

        private void initRule(){
            sfYear = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
            sfHour = new SimpleDateFormat("HH:mm:ss",Locale.getDefault());
        }

        public void bindDataInView(AlarmBean alarmBean){
            alarmName.setText(alarmBean.getContent());
            alarmState.setText(alarmBean.getHandleState());
            alarmValue.setText(String.valueOf(alarmBean.getValue()));
            alarmTimeYear.setText(sfYear.format(alarmBean.getTime()));
            alarmTimeHour.setText(sfHour.format(alarmBean.getTime()));
        }
    }

    //refresh view 的adapter
    private class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
        private List<AlarmBean> mdatas;

        public MyAdapter(List<AlarmBean> mdatas){
            this.mdatas = mdatas;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.alarm_item_view,parent,false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            AlarmBean itemData = mdatas.get(position);
            holder.bindDataInView(itemData);
        }

        @Override
        public int getItemCount() {
            return mdatas.size();
        }

        //清空数据
        public void clearContent(){
            mdatas.clear();
            this.notifyDataSetChanged();
        }
    }

    //获取当前报警列表，并填充
    private void getAlarmNow(){
        GuiwuApi.queryCurrentAlarm(gateWaySn, new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG ,"当前报警请求成功" + response);
                JsonArray jsonArray = activityParent.getJsonAry(response,"获取当前报警",TAG);
                alarmNowShow.clear();
                alarmNowShow.addAll(analyseReturn(jsonArray));
                alarmShowCopy.clear();
                alarmShowCopy.addAll(alarmNowShow);
               // refreshAdapter.notifyDataSetChanged();
                MyLog.i(TAG ,"解析结果成功" + alarmNowShow.size());
                for (AlarmBean alarmBean : alarmNowShow){
                    alarmBean.setContext(getContext());
                }
                updateUI();
                refreshView.refreshComplete();
            }

            @Override
            public void onFailed(Exception e) {

            }
        });
    }

    //分析报警返回信息
    private List<AlarmBean> analyseReturn(JsonArray jsonArray){
        if (jsonArray == null)
            return new ArrayList<AlarmBean>();
        Gson gson = new Gson();
        return gson.fromJson(jsonArray, new TypeToken<List<AlarmBean>>() {}.getType());
    }

    //查询历史报警记录，并填充
    private void getAlarmHistory(){
        GuiwuApi.queryHistoryAlarm(gateWaySn, dateStart, dateNow, new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG ,"历史报警请求成功" + response);
                JsonArray jsonArray = activityParent.getJsonAry(response,"获取历史报警",TAG);
                alarmHistory = analyseReturn(jsonArray);
                if (alarmHistory == null)
                    alarmHistory = new ArrayList<>();
                for (AlarmBean alarmBean :alarmHistory){
                    alarmBean.setContext(getContext());
                    alarmBean.setHandleState(0);
                }
                alarmNowShow.clear();
                alarmNowShow.addAll(alarmHistory);
                alarmShowCopy.clear();
                alarmShowCopy.addAll(alarmNowShow);
                MyLog.i(TAG ,"解析结果成功" + alarmNowShow.size());
                updateUI();
                refreshView.refreshComplete();
            }

            @Override
            public void onFailed(Exception e) {

            }
        });
    }


    private void queryMatchShow(String keyWords){
        List<AlarmBean> findAlarms = queryMatch(keyWords);
        alarmNowShow.clear();
        alarmNowShow.addAll(findAlarms);
        refreshAdapter.notifyDataSetChanged();
    }

    private List<AlarmBean> queryMatch(String keyWords){
        List<AlarmBean> returnList = new ArrayList<>();
        if (alarmShowCopy.size() == 0)
            return returnList;
        for (int i = 0 ,length = alarmShowCopy.size() ;i<length ;i++){
            if( alarmShowCopy.get(i).getContent().contains(keyWords))
                returnList.add(alarmShowCopy.get(i));
        }
        return returnList;
    }


    public static MonitorAlarmFragment newInstance(String gateWaySn) {
        Bundle args = new Bundle();
        args.putString(MonitorActivity.GATEWAY_SN,gateWaySn);
        MonitorAlarmFragment fragment = new MonitorAlarmFragment();
        fragment.setArguments(args);
        return fragment;
    }



}
